<template>
  <canvas ref="canvasRef"></canvas>
</template>
  
  <script setup>
import myBox from "./my-box.js";
import { ref, onMounted } from "vue";
import {
  WebGLRenderer,
  PerspectiveCamera,
  DirectionalLight,
  Scene,
  MeshPhongMaterial,
  Mesh,
} from "three";

const canvasRef = ref(null);

const createMaterial = () => {
  const material = new MeshPhongMaterial();
  const h = Math.floor(Math.random() * 100) / 100;
  const s = 1;
  const l = 0.5;
  material.color.setHSL(h, s, l);
  return material;
};

onMounted(() => {
  // 创建渲染器
  const renderer = new WebGLRenderer({ canvas: canvasRef.value });
  // 创建场景
  const scene = new Scene();
  // 创建镜头
  const camera = new PerspectiveCamera(40, 2, 0.1, 1000);
  camera.position.z = 120;
  // 创建光源
  const light1 = new DirectionalLight(0xffffff, 1);
  light1.position.set(-1, 2, 4);
  scene.add(light1);
  const light2 = new DirectionalLight(0xffffff, 1);
  light2.position.set(1, -2, -4);
  scene.add(light2);

  const solidPrimitivesArr = []; // 所有的几何体
  solidPrimitivesArr.push(myBox);

  const meshArr = []; // 所有的网格单元
  solidPrimitivesArr.forEach((item) => {
    const material = createMaterial();
    const mesh = new Mesh(item, material);
    meshArr.push(mesh);
  });

  const eachRow = 5;
  const spread = 15;
  meshArr.forEach((mesh, index) => {
    const row = Math.floor(index / eachRow);
    const column = index % eachRow;
    mesh.position.x = (column - 2) * spread;
    mesh.position.y = (2 - row) * spread;

    scene.add(mesh);
  });

  renderer.render(scene, camera);
});
</script>
  
  <style scoped>
canvas {
  display: block;
  width: inherit;
  height: inherit;
}
</style>